package com.logistics.controller.tenant;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.logistics.common.Result;
import com.logistics.entity.SysRole;
import com.logistics.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 角色管理控制器
 */
@RestController
@RequestMapping("/tenant/role")
public class RoleController {
    
    @Autowired
    private RoleService roleService;
    
    /**
     * 分页查询角色列表
     */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('r3t8q5l9') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<IPage<SysRole>> getRoleList(
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String keyword) {
        IPage<SysRole> result = roleService.getRoleList(current, size, keyword);
        return Result.success(result);
    }
    
    /**
     * 获取角色的权限列表（返回权限代码）
     */
    @GetMapping("/{id}/permissions")
    @PreAuthorize("hasAuthority('r3t8q5l9') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<List<String>> getRolePermissions(@PathVariable Long id) {
        List<String> permissionCodes = roleService.getRolePermissions(id);
        return Result.success(permissionCodes);
    }
    
    /**
     * 创建角色
     */
    @PostMapping
    @PreAuthorize("hasAuthority('k7w2f6b4') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<SysRole> createRole(@RequestBody SysRole role) {
        SysRole created = roleService.createRole(role);
        return Result.success(created);
    }
    
    /**
     * 更新角色
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('p1m9x5v8') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<Void> updateRole(@PathVariable Long id, @RequestBody SysRole role) {
        role.setId(id);
        roleService.updateRole(role);
        return Result.success(null);
    }
    
    /**
     * 删除角色
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('q6j3h7c1') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<Void> deleteRole(@PathVariable Long id) {
        roleService.deleteRole(id);
        return Result.success(null);
    }
    
    /**
     * 为角色分配权限（接收权限代码列表）
     */
    @PutMapping("/{id}/permissions")
    @PreAuthorize("hasAuthority('y4n8g2z9') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<Void> assignPermissions(
            @PathVariable Long id,
            @RequestBody Map<String, List<String>> request) {
        List<String> permissionCodes = request.get("permissionCodes");
        roleService.assignPermissions(id, permissionCodes);
        return Result.success(null);
    }
}

